const express = require("express");
const multer = require('multer');
const OSS = require('ali-oss');
// const aiService = require("./aiService");
require('dotenv').config();
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true, limit: "10mb" }));

// app.post("/api/image-recognition", (req, res) => {
//   const { base64 } = req.body;
//   console.log("/api/image-recognition");
//   aiService.recognizeImageContent(base64).then((completion) => {
//     console.log(completion.choices[0].message.content);
//     res.send({
//       msg: completion.choices[0].message.content,
//     });
//   });
// });

const upload = multer({ dest: 'uploads/' });

// 配置OSS客户端
const client = new OSS({
  region: process.env.OSS_REGION, // 例如：'oss-cn-hangzhou'
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET_NAME
});

// 文件上传路由
app.post('/upload', upload.single('file'), async (req, res) => {
  try {
    // 上传文件到OSS
    const result = await client.put(`/${req.file.originalname}`, req.file.path);

    // 生成临时访问URL
    const url = await client.signatureUrl(`/${req.file.originalname}`, {
      expires: 3600, // URL有效期为1小时
      process: '' // 可选参数，用于指定图片处理等
    });

    // 返回文件的临时URL
    res.json({
      message: 'File uploaded successfully.',
      url: url
    });
  } catch (error) {
    console.error(error);
    res.status(500).send('Failed to upload file.');
  }
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
